package com.csdj.rest.controller;

import com.csdj.beans.entity.User;
import com.csdj.beans.interfaces.user.IUserService;
import com.csdj.common.WebResult;
import com.csdj.common.WsCommand;
import com.csdj.common.constant.CommonConstant;
import com.csdj.common.constant.WebResultConstant;
import com.csdj.rest.service.ConfigService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

//    @DubboReference
    private IUserService userService;
    @Resource
    private ConfigService configService;

    @PostMapping("/login")
    public WebResult login(@RequestParam(value = "username",required = true) String username,
                           @RequestParam(value = "password",required = true) String password){
        final User user = userService.login(username, password);
        if(user == null){
            return WebResult.fail(WebResultConstant.USER_OR_PASSWORD_ERROR);
        }
        return WebResult.success(user);
    }
    @GetMapping("/list")
    public WebResult getUserList(Byte type,Byte status,String role,Integer page,Integer rows){
        long total = userService.getListTotal(type,status,role);
        return WebResult.success(userService.getList(type,status,role,page,rows))
                .putData("total",total);
    }


    @GetMapping("/info")
    public WebResult getInfo(HttpServletRequest request){
        String uid = request.getHeader(CommonConstant.HEADER_USER_ID);
        return WebResult.success(userService.getById(Integer.parseInt(uid)));
    }

    @GetMapping("/qrcode")
    public WebResult getLoginCode(String sessionId){
        String code = userService.getQrLoginCode(sessionId);
        return WebResult.success(code);

    }

    /**
     * 扫码登录 向websocket返回uid,token
     * @param request
     * @param code
     * @return
     */
    @PostMapping("/qrcode")
    public WebResult checkQrcode(HttpServletRequest request,String code,String sessionId){
        String uid = request.getHeader(CommonConstant.HEADER_USER_ID);
        User user = userService.checkQrCode(Integer.parseInt(uid),sessionId,code);
        if(user == null){
            //websocket 给页面返回数据
            return WebResult.fail(WebResultConstant.QRCODE_NO);
        }
        String token = request.getHeader(CommonConstant.HEADER_TOKEN);
        Map<String,String> map = new HashMap<>();
        map.put("uid",uid);
        map.put("token",token);
        WsCommand command = new WsCommand();
        command.setCmd("login_redirect");
        command.setData(map);
        WebSocketController.sendMessage(sessionId,command);
        return WebResult.success("success");
    }
}
